<?php
namespace App\Service\Admin;

class QrService extends BaseService
{
    //码

    //列表
    public static function index($pages)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = self::dbConn(self::$dbQr);
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])
            ->orderBy('id', 'asc')
            ->get();
        if (!count($res)) {
            return self::toback(0, '', [], $total);
        }
        $types = self::$cateTypes;
        foreach ($res as &$v) {
            $v->type_name = array_key_exists($v->yw_type, $types) ? $types[$v->yw_type] : '';
            $v->qrlink = env('DOMAIN') . '/h5/?c=' . $v->code;
            $v->scan_total = self::dbConn(self::$dbQrlog)->where('code', $v->code)->count();
        }
        return self::toback(0, '', $res, $total);
    }

    //扩充
    public static function add()
    {
        for ($i = 0; $i < 100; $i ++) {
            $code = self::code();
            self::dbConn(self::$dbQr)->insertGetId([
                'code' => $code, 'show_code' => toCode(), 'addtime' => toDate(),
            ]);
        }
        return self::toback();
    }

    //获取码值
    public static function code()
    {
        $code = toRandStr(rand(4, 8));
        $qrOne = self::dbConn(self::$dbQr)->where('code', $code)->first();
        if ($qrOne) {
            return self::code();
        }
        return $code;
    }

    //扫码记录
    public static function qrlog($pages, $code)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = self::dbConn(self::$dbQrlog);
        if ($code) {
            $db = $db->where('code', $code);
        }
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])
            ->orderBy('id', 'asc')
            ->get();
        if (!count($res)) {
            return self::toback(0, '', [], $total);
        }
        foreach ($res as &$v) {
            $qrOne = self::dbConn(self::$dbQr)->where('code', $v->code)->first();
            $uOne = self::dbConn(self::$dbWx)->where('id', $v->uid)->first();
            $v->show_code = $qrOne ? $qrOne->show_code : '';
            $uname = $uOne ? $uOne->nickName : '';
            $v->uname = $v->h5code.'【'.$uname.'】';
        }
        return self::toback(0, '', $res, $total);
    }
}